package cn.omisheep.au.core.filter;

import cn.omisheep.au.annotation.AuUser;
import cn.omisheep.au.core.AuFactory;
import cn.omisheep.au.core.JwtHelper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 执行顺序 1.AuFilter  2.AuHandlerMethodArgumentResolver
 * 如果有权限判断则先进行权限判断，如果判断成功，才去数据库获得user，（以@AuUser标记过的字段）
 *
 * @author zhou xin chen  😊
 * 联系方式 qq:1269670415  email:xinchenzhou666@gmail.com
 */
@SuppressWarnings("all")
@Slf4j
public class AuUserResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private AuFactory auFactory;

    @Autowired
    private JwtHelper jwtHelper;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(AuUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest nativeWebRequest, WebDataBinderFactory binderFactory) throws Exception {
        AuUser auUser = parameter.getParameterAnnotation(AuUser.class);
        Claims claims;

        if (auUser.authority()) {
            claims = (Claims) nativeWebRequest.getAttribute("au-info", 0);
            if (claims == null) return null;
        } else {
            try {
                String token = nativeWebRequest.getHeader("authorization");
                claims = jwtHelper.parseToken(token);
            } catch (Exception e) {
                return null;
            }
        }
        return auFactory.getUser(parameter, claims);
    }

}
